/**
 * 工作记录 Composable
 */
import { ref, computed } from 'vue'

export function useWorkRecords() {
  // 响应式数据
  const workTimes = ref([])
  const workLoading = ref(false)
  const workError = ref('')
  const isWorking = ref(false)
  const currentWorkStart = ref(null)

  // 计算属性
  const showWorkControls = computed(() => {
    // 这个计算属性需要从外部传入taskData，或者改为通过参数传入
    return false // 暂时返回false，需要在调用时传入taskData
  })

  const totalWorkTime = computed(() => {
    if (!workTimes.value || workTimes.value.length === 0) return 0
    
    let totalMinutes = 0
    workTimes.value.forEach(workTime => {
      try {
        const startTime = new Date(workTime.startTime || workTime.start_at || workTime.start)
        const endTime = new Date(workTime.endTime || workTime.end_at || workTime.end)
        
        if (!isNaN(startTime.getTime()) && !isNaN(endTime.getTime())) {
          const duration = endTime.getTime() - startTime.getTime()
          totalMinutes += Math.floor(duration / (1000 * 60))
        }
      } catch (error) {
        console.error('计算工作时长失败:', error)
      }
    })
    
    return totalMinutes
  })

  const formatWorkTime = (minutes) => {
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const remainingMinutes = minutes % 60
      return `${hours}小时${remainingMinutes}分钟`
    }
  }

  // 方法
  const fetchWorkTimes = async (taskId) => {
    if (!taskId) return

    workLoading.value = true
    workError.value = ''

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/work-time/task/${taskId}`,
        method: 'GET',
        header: {
          'Access-Token': `Bearer ${token}`
        }
      })

      if (response.data && response.data.success) {
        workTimes.value = response.data.data || []
      }
    } catch (err) {
      workError.value = err.message || '获取工作记录失败'
      console.error('获取工作记录失败:', err)
    } finally {
      workLoading.value = false
    }
  }

  const startWork = async (taskId) => {
    if (!taskId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/work-time/start',
        method: 'POST',
        data: {
          taskId: taskId
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        isWorking.value = true
        currentWorkStart.value = new Date()
        uni.showToast({
          title: '开始工作',
          icon: 'success'
        })
        // 刷新工作记录
        await fetchWorkTimes(taskId)
        return true
      } else {
        throw new Error(response.data?.message || '开始工作失败')
      }
    } catch (err) {
      console.error('开始工作失败:', err)
      uni.showToast({
        title: err.message || '开始工作失败',
        icon: 'none'
      })
      return false
    }
  }

  const endWork = async (taskId, description = '') => {
    if (!taskId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/work-time/end',
        method: 'POST',
        data: {
          taskId: taskId,
          description: description
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        isWorking.value = false
        currentWorkStart.value = null
        uni.showToast({
          title: '结束工作',
          icon: 'success'
        })
        // 刷新工作记录
        await fetchWorkTimes(taskId)
        return true
      } else {
        throw new Error(response.data?.message || '结束工作失败')
      }
    } catch (err) {
      console.error('结束工作失败:', err)
      uni.showToast({
        title: err.message || '结束工作失败',
        icon: 'none'
      })
      return false
    }
  }

  const formatDateTime = (dateTime) => {
    if (!dateTime) return '未知'
    
    try {
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    } catch (error) {
      return '格式错误'
    }
  }

  const calculateDuration = (workTime) => {
    try {
      const startTime = new Date(workTime.startTime || workTime.start_at || workTime.start)
      const endTime = new Date(workTime.endTime || workTime.end_at || workTime.end)
      
      if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
        return '计算错误'
      }
      
      const duration = endTime.getTime() - startTime.getTime()
      const hours = Math.floor(duration / (1000 * 60 * 60))
      const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      } else {
        return `${minutes}分钟`
      }
    } catch (error) {
      return '计算错误'
    }
  }

  return {
    // 响应式数据
    workTimes,
    workLoading,
    workError,
    isWorking,
    currentWorkStart,
    
    // 计算属性
    showWorkControls,
    totalWorkTime,
    
    // 方法
    fetchWorkTimes,
    startWork,
    endWork,
    formatDateTime,
    calculateDuration,
    formatWorkTime
  }
}
